package servlet;

import entity.Book;
import service.BookService;
import service.impl.BookServiceImpl;
import utils.Pager;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.List;

@WebServlet(urlPatterns = {"/BookServlet","/book"})
public class BookServlet extends HttpServlet {
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        //1.获取当前页索引
        String currentPage = request.getParameter("pageIndex");
        //1.1如果当前页的值为null,则默认为第1页
        int pageIndex = currentPage == null ? 1 : Integer.parseInt(currentPage);
        //2.设置每页显示的条数
        int pageSize = 10;
        //3.创建业务层的操作对象
        BookService bookService = new BookServiceImpl();
        //4.调用查询图书总条数的查询方法
        int totalCount = bookService.getTotalCount();
        //5.计算总页数 100   10   10 |  101   10   11
        int totalPage = totalCount % pageSize == 0 ? (totalCount / pageSize) : (totalCount / pageSize) + 1;
        //6.调用分页查询图书集合
        List<Book> books = bookService.findByPage(pageIndex, pageSize);
        //7.封装服务端分页数据信息到Pager对象中
        Pager<Book> pagerInfo = new Pager<Book>(pageIndex, pageSize, totalCount, totalPage, books);
        //8.存储数据到request作用域中
        request.setAttribute("pagerInfo", pagerInfo);
        //9.转发，跳转至图书首页
        request.getRequestDispatcher("index.jsp").forward(request, response);

    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doPost(request, response);
    }
}
